package com.sem.example2.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketClient {

	/**
	 * 客户端Socket构造方法
	 */
	public SocketClient() {
		BufferedReader sysin = null;
		PrintWriter out = null;
		BufferedReader in = null;
		ReadDataListening serverListening = null;
		Thread serverListeningThread = null;
		String name = null;
		try {

			// 向本机的2121端口发出客户请求
			Socket socket = new Socket("localhost", 2121);

			System.out.print("请输入名称：");

			// 由系统标准输入设备构造BufferedReader对象
			sysin = new BufferedReader(new InputStreamReader(System.in));

			// 由Socket对象得到输出流,并构造PrintWriter对象
			out = new PrintWriter(socket.getOutputStream());

			// 由Socket对象得到输入流,并构造相应的BufferedReader对象
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

			String line; // 保存一行内容

			// 从系统标准输入读入一字符串
			line = sysin.readLine();

			while (true) { // 若从标准输入读入的字符串为 "bye"则停止循环

				if (!line.equals("bye")) {
					if (serverListening == null) {
						name = line;
						serverListening = new ReadDataListening(name, in);
						serverListening.setListening(true);
						serverListeningThread = new Thread(serverListening);
						serverListeningThread.start();
					} else {
						// 将从系统标准输入读入的字符串输出到Server
						line = "[" + name + "]: " + line;
					}
					out.println(line);

					// 刷新输出流,使Server马上收到该字符串
					out.flush();

					// 在系统标准输出上打印读入的字符串
					System.out.println(line);

					// 从Server读入一字符串，并打印到标准输出上
					// System.out.println("[Server]: " + in.readLine());
					// 从系统标准输入读入一字符串
					line = sysin.readLine();
				} else {
					serverListening.setListening(false);
					break;
				}
			}

			// out.close(); // 关闭Socket输出流
			// in.close(); // 关闭Socket输入流
			// socket.close(); // 关闭Socket
		} catch (Exception e) {
			System.out.println("Error. " + e);
			e.printStackTrace();
		} finally {
			if (sysin != null) {
				try {
					sysin.close(); // 关闭控制台输入流
				} catch (IOException e) {
					System.err.println("Socket控制台输入流关闭异常，失败");
					e.printStackTrace();
				}
			}
			if (out != null) {
				out.close(); // 关闭Socket输出流
			}
			if (in != null) {
				try {
					in.close();// 关闭Socket输入流
				} catch (IOException e) {
					System.err.println("Socket输入流关闭异常，失败");
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 主方法
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		new SocketClient();
	}

}
